package com.feimaopian.controller;

import com.alibaba.fastjson.JSONObject;
import com.feimaopian.entity.User;
import com.feimaopian.service.UserServiceImpl;
import com.feimaopian.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserServiceImpl userMapper;

    @PostMapping("/login")
    public JSONObject login(@RequestBody String param) {
        JSONObject json = JSONObject.parseObject(param);
        if (json == null) {
            System.out.println("json == null");
            json.put("success", 0);
            return json;
        }

        String user_id = json.getString("user_id");
        String password = json.getString("pwd");
        json.clear();

        if (user_id == null || password == null) {
            System.out.println("user_id == null || password == null");
            json.put("success", 0);
            return json;
        }

        if (userMapper.eq(user_id, password)) {
            Map<String, String> chaim = new HashMap<>();
            chaim.put("username", user_id);
            String token = JwtUtils.create(chaim);

            json.put("success", 1);
            json.put("user_id", userMapper.findById(user_id).getUser_id());
            json.put("username", userMapper.findById(user_id).getUsername());
            json.put("token", token);
        } else {
            System.out.println("用户名密码不对" + "用户名：" + user_id + "密码：" + password);
            json.put("success", 0);
        }
        return json;


    }

    @PostMapping("/add")
    public boolean addUser(@RequestBody User user) {
        if (user == null) {
            return false;
        }
        return userMapper.addUser(user) == 1;
    }
}